﻿using DeviceMaintainGIS.Entity;
using DeviceMaintainGIS.Model.DevProRelation;
using DeviceMaintainGIS.Model.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace AchieveManageWeb.Controllers
{
    public class DevProRelationController : Controller
    {
        //
        // GET: /DevProRelation/

        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 设备关系添加页
        /// </summary>
        /// <returns></returns>
        public ActionResult DevProRelationAdd()
        {

            ViewBag.CodeTypeList = GetCodeType();

            return View();
        }


        /// <summary>
        /// 设备编辑页
        /// </summary>
        /// <returns></returns>
        public ActionResult DevProRelationEdit()
        {
            DevProRelationInfoModel dprim = new DevProRelationInfoModel();
            using (CYOADBEntities Entities = new CYOADBEntities())
            {

                ViewBag.CodeTypeList = GetCodeType();
                string DeviceId = Request["DeviceId"] == null ? "1" : Request["DeviceId"].ToString();
                var linqs = from a in Entities.DevProRelation_Tab.Where(i => i.DeviceId == DeviceId)
                            join f in Entities.DevInfo_Tab on a.DeviceId equals f.DeviceId
                            into tmpDevInfo
                            let k = tmpDevInfo.FirstOrDefault()
                            select new DevProRelationInfoModel
                            {
                                DPRelationId = a.DPRelationId,
                                DeviceId = a.DeviceId,
                                CodeId = a.CodeId,
                                Code = a.Code,
                                ReName = a.ReName,
                                LocaId = a.LocaId,
                                Remark = a.Remark,
                                WarrantyTime = a.WarrantyTime,
                                State = k.State,
                                DeviceName = k.DeviceName,
                                ChangeDateTime = k.State == 1 ? a.OutTime : a.ScrapTime,
                            };
                dprim = linqs.FirstOrDefault();
            };
            return View(dprim);
        }
        /// <summary>
        /// 获取出库类型
        /// </summary>
        /// <returns></returns>
        public List<CodeType> GetCodeType()
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.CodeType_Tab
                           select new CodeType
                           {
                               CodeId = a.CodeId,
                               CodeTypeName = a.CodeType
                           };
                List<CodeType> list = linq.ToList();

                return list;
            }
        }
        /// <summary>
        /// 获取基站信息
        /// </summary>
        /// <returns></returns>
        public string GetSelLocaInfo()
        {
            string strJson = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.LocaInfo_Tab
                           select new LocaInfo
                           {
                               id = a.LocaId,
                               text = a.LocaName,

                           };
                List<LocaInfo> SelDevInfoModelList = linq.ToList();
                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(SelDevInfoModelList);
            }
            return strJson;
        }
        /// <summary>
        /// 获取设备信息
        /// </summary>
        /// <returns></returns>
        public string GetSelDevInfo()
        {
            string strJson = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.DevInfo_Tab.Where(i => i.State == 0 && i.DeviceLevel == 1)
                           select new SelDevInfoModel
                           {
                               id = a.DeviceId,
                               text = a.DeviceName + "(" + a.CompanySerial + ")",
                               WarrantyTime = a.WarrantyTime
                           };
                List<SelDevInfoModel> SelDevInfoModelList = linq.ToList();
                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(SelDevInfoModelList);
            }
            return strJson;
        }

        /// <summary>
        /// 根据条件查询设备关系信息
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllDevProRelation()
        {


            //首先获取前台传递过来的参数
            int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);

            string selReName = Request["selReName"] == null ? "" : Request["selReName"].ToString();
            string selCompanySerial = Request["selCompanySerial"] == null ? "" : Request["selCompanySerial"].ToString();
            string selCModelSize = Request["selCModelSize"] == null ? "" : Request["selCModelSize"].ToString();
            int selDevState = Request["selDevState"] == null || Request["selDevState"].ToString() == "" ? 1 : int.Parse(Request["selDevState"].ToString());
            DateTime tmp = DateTime.ParseExact("19000101", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
            DateTime selStartWarrantyTime = Request["selStartWarrantyTime"] == null || Request["selStartWarrantyTime"].ToString() == "" ? tmp : DateTime.Parse(Request["selStartWarrantyTime"].ToString());
            DateTime selEndWarrantyTime = Request["selEndWarrantyTime"] == null || Request["selEndWarrantyTime"].ToString() == "" ? tmp : DateTime.Parse(Request["selEndWarrantyTime"].ToString());

            string strJson;
            int totalCount;   //输出参数
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                var linq = from a in Entities.DevInfo_Tab.Where(i => i.State != 0 && i.DeviceLevel == 1)
                           join m in Entities.DevType_Tab on a.DeviceTypeId equals m.DeviceTypeId
                            into tmpLocaType
                           let s = tmpLocaType.FirstOrDefault()

                           join f in Entities.DevProRelation_Tab on a.DeviceId equals f.DeviceId
                            into tmpDevProRelation
                           let k = tmpDevProRelation.FirstOrDefault()

                           join b in Entities.CodeType_Tab on k.CodeId equals b.CodeId
                            into tmpCodeType
                           let c = tmpCodeType.FirstOrDefault()

                           join e in Entities.LocaInfo_Tab on k.LocaId equals e.LocaId
                            into tmpLocaInfo
                           let m = tmpLocaInfo.FirstOrDefault()
                           select new DevProRelationModel
                           {
                               DeviceId = a.DeviceId,
                               DeviceName = a.DeviceName,
                               DeviceTypeId = a.DeviceTypeId,
                               DeviceTypeName = s == null ? "" : s.DeviceName,
                               FactorySerial = a.FactorySerial,
                               CompanySerial = a.CompanySerial,
                               FModelSize = a.FModelSize,
                               CModelSize = a.CModelSize,
                               Purchaser = a.Purchaser,
                               PurchaseTime = a.PurchaseTime,
                               PurchaseWarrantyTime = a.WarrantyTime,
                               WarrantyTime = k.WarrantyTime,
                               DeviceFactory = a.DeviceFactory,
                               DeviceTel = a.DeviceTel,
                               State = a.State,
                               CodeTypeName = c.CodeType,
                               ReName = k.ReName,
                               OutTime = a.State == 2 ? k.ScrapTime : k.OutTime,
                               //ScrapTime = k.ScrapTime,
                               Remark = k.Remark,
                               LocaName = m == null ? "" : m.LocaName,
                               DeviceLevel = a.DeviceLevel,
                           };



                //设备名称
                if (!string.IsNullOrEmpty(selReName))
                {
                    linq = linq.Where(i => i.ReName.Contains(selReName));
                }
                //公司序列号
                if (!string.IsNullOrEmpty(selCompanySerial))
                {
                    linq = linq.Where(i => i.CompanySerial.Contains(selCompanySerial));
                }
                //公司规格型号
                if (!string.IsNullOrEmpty(selCModelSize))
                {
                    linq = linq.Where(i => i.CModelSize.Contains(selCModelSize));
                }
                //质保期
                if (selStartWarrantyTime != tmp && selEndWarrantyTime != tmp)
                {
                    linq = linq.Where(a => a.WarrantyTime >= selStartWarrantyTime && a.WarrantyTime <= selEndWarrantyTime);
                }
                //设备状态

                linq = linq.Where(i => i.State == selDevState);
                totalCount = linq.Count();
                List<DevProRelationModel> list = linq.OrderBy(i => i.DeviceId).Take(pagesize * pageindex).Skip(pagesize * (pageindex - 1)).ToList();

                JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
                strJson = jsonSerialize.Serialize(list);

            };

            var jsonResult = new { total = totalCount.ToString(), rows = strJson };
            return Content("{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}");
        }

        /// <summary>
        /// 添加设备关系信息
        /// </summary>
        /// <param name="drim"></param>
        /// <returns></returns>
        public ActionResult DevProRelationInfoAdd(DevProRelationInfoModel drim)
        {
            int code = 0;
            string newID = Guid.NewGuid().ToString();
            DevProRelation_Tab dprt = new DevProRelation_Tab();
            dprt.DPRelationId = newID;
            dprt.DeviceId = drim.DeviceId;
            dprt.CodeId = drim.CodeId;
            dprt.Code = drim.Code;

            dprt.LocaId = drim.LocaId;
            dprt.Remark = drim.Remark;
            dprt.WarrantyTime = drim.WarrantyTime;
            if (drim.State == (int)DevState.TheLibrary)
            {
                dprt.OutTime = drim.ChangeDateTime;
            }
            else
            {
                dprt.ScrapTime = drim.ChangeDateTime;
            }

            dprt.AddTime = System.DateTime.Now;


            using (CYOADBEntities Entities = new CYOADBEntities())
            {

                int Count = Entities.DevProRelation_Tab.Where(i => i.DeviceId == drim.DeviceId).Count();
                if (Count > 1)
                {
                    return Content("{\"msg\":\"添加失败！设备关系已存在！\",\"success\":false}");
                }
                if (drim.CodeId == "1")
                {
                    int ProCount = Entities.ProInfo_Tab.Where(i => i.ProjectId == drim.Code).Count();
                    if (ProCount < 1)
                    {
                        return Content("{\"msg\":\"添加失败！输入的项目编号不存在！\",\"success\":false}");
                    }
                }
                DevInfo_Tab DevModel = Entities.DevInfo_Tab.Where(i => i.DeviceId == drim.DeviceId).FirstOrDefault();
                if (!string.IsNullOrEmpty(drim.ReName))
                {
                    dprt.ReName = drim.ReName;
                }
                else
                {
                    dprt.ReName = DevModel.DeviceName;
                }
                Entities.DevProRelation_Tab.Add(dprt);
                Entities.Entry<DevProRelation_Tab>(dprt).State = System.Data.Entity.EntityState.Added;
                code = Entities.SaveChanges();
                if (code > 0)
                {

                    DevModel.State = drim.State;

                    Entities.DevInfo_Tab.Add(DevModel);
                    Entities.Entry<DevInfo_Tab>(DevModel).State = System.Data.Entity.EntityState.Modified;
                    code = Entities.SaveChanges();
                    SetSonDevInfo(DevModel.ID, DevModel.DeviceId, drim.State);
                    return Content("{\"msg\":\"添加成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"添加失败！入库失败\",\"success\":false}");
                }
            }
        }
        /// <summary>
        /// 设置设备的子设备状态
        /// </summary>
        /// <param name="DeviceId"></param>
        /// <returns></returns>
        public string SetSonDevInfo(int ID, string DeviceId, int State)
        {
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //获取设备的关系
                DevTpRelation_Tab DevTpRelation = Entities.DevTpRelation_Tab.Where(i => i.DeviceId == ID).FirstOrDefault();
                string DevPath = "";
                if (DevTpRelation != null)
                {
                    DevPath = DevTpRelation.Path;
                }
                else
                {
                    DevPath = ID + ",";
                }
                //获取当前设备下的所有子设备
                List<DevTpRelation_Tab> DevTpRelationTabList = Entities.DevTpRelation_Tab.Where(i => i.Path.StartsWith(DevPath) && i.DeviceId != ID).ToList();
                //获取主出库信息
                DevProRelation_Tab DevProRelation = Entities.DevProRelation_Tab.Where(i => i.DeviceId == DeviceId).FirstOrDefault();

                if (DevTpRelationTabList.Count > 0)
                {
                    foreach (DevTpRelation_Tab dtrt in DevTpRelationTabList)
                    {
                        DevInfo_Tab sonDevModel = Entities.DevInfo_Tab.Where(i => i.ID == dtrt.DeviceId).FirstOrDefault();
                        sonDevModel.State = State;

                        Entities.DevInfo_Tab.Add(sonDevModel);
                        Entities.Entry<DevInfo_Tab>(sonDevModel).State = System.Data.Entity.EntityState.Modified;
                        //获取设备出库信息
                        DevProRelation_Tab sonDevProRelation = Entities.DevProRelation_Tab.Where(i => i.DeviceId == sonDevModel.DeviceId).FirstOrDefault();
                        if (State == 0)
                        {
                            if (sonDevProRelation != null)
                            {
                                Entities.DevProRelation_Tab.Add(sonDevProRelation);
                                Entities.Entry<DevProRelation_Tab>(sonDevProRelation).State = System.Data.Entity.EntityState.Deleted;
                            }
                        }
                        else
                        {
                            if (sonDevProRelation != null)
                            {
                                sonDevProRelation.CodeId = DevProRelation.CodeId;
                                sonDevProRelation.Code = DevProRelation.Code;
                                sonDevProRelation.ReName = DevProRelation.ReName;
                                sonDevProRelation.LocaId = DevProRelation.LocaId;
                                sonDevProRelation.Remark = DevProRelation.Remark;
                                sonDevProRelation.WarrantyTime = DevProRelation.WarrantyTime;
                                if (sonDevModel.State == (int)DevState.Scrap)
                                {
                                    sonDevProRelation.OutTime = DevProRelation.OutTime;
                                }

                                Entities.DevProRelation_Tab.Add(sonDevProRelation);
                                Entities.Entry<DevProRelation_Tab>(sonDevProRelation).State = System.Data.Entity.EntityState.Modified;
                            }
                            else
                            {
                                sonDevProRelation = new DevProRelation_Tab();
                                string newID = Guid.NewGuid().ToString();
                                sonDevProRelation.DPRelationId = newID;
                                sonDevProRelation.CodeId = DevProRelation.CodeId;
                                sonDevProRelation.DeviceId = sonDevModel.DeviceId;
                                sonDevProRelation.Code = DevProRelation.Code;
                                sonDevProRelation.ReName = DevProRelation.ReName;
                                sonDevProRelation.LocaId = DevProRelation.LocaId;
                                sonDevProRelation.Remark = DevProRelation.Remark;
                                sonDevProRelation.WarrantyTime = DevProRelation.WarrantyTime;
                                sonDevProRelation.WarrantyTime = DevProRelation.WarrantyTime;
                                if (sonDevModel.State == (int)DevState.TheLibrary)
                                {
                                    sonDevProRelation.OutTime = DevProRelation.OutTime;
                                }
                                else
                                {
                                    sonDevProRelation.ScrapTime = DevProRelation.ScrapTime;
                                }

                                sonDevProRelation.AddTime = System.DateTime.Now;
                                Entities.DevProRelation_Tab.Add(sonDevProRelation);
                                Entities.Entry<DevProRelation_Tab>(sonDevProRelation).State = System.Data.Entity.EntityState.Added;
                            }
                        }
                    }
                }

                Entities.SaveChanges();
            }
            return "";
        }

        /// <summary>
        /// 设备关系编辑
        /// </summary>
        /// <param name="drim"></param>
        /// <returns></returns>
        public ActionResult DevProRelationInfoEdit(DevProRelationInfoModel drim)
        {
            int code = 0;

            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                if (drim.CodeId == "1")
                {
                    int ProCount = Entities.ProInfo_Tab.Where(i => i.ProjectId == drim.Code).Count();
                    if (ProCount < 1)
                    {
                        return Content("{\"msg\":\"保存失败！输入的项目编号不存在！\",\"success\":false}");
                    }
                }

                //获取当前设备的关系信息
                DevProRelation_Tab dprt = Entities.DevProRelation_Tab.Where(i => i.DPRelationId == drim.DPRelationId).FirstOrDefault();

                dprt.CodeId = drim.CodeId;
                dprt.Code = drim.Code;
                dprt.ReName = drim.ReName;
                dprt.LocaId = drim.LocaId;
                dprt.Remark = drim.Remark;
                dprt.WarrantyTime = drim.WarrantyTime;
                drim.State = drim.State;
                if (drim.State == (int)DevState.Scrap)
                {
                    dprt.OutTime = drim.ChangeDateTime;
                }
                if (drim.State == 0)
                {
                    Entities.DevProRelation_Tab.Add(dprt);
                    Entities.Entry<DevProRelation_Tab>(dprt).State = System.Data.Entity.EntityState.Deleted;
                }
                else
                {
                    Entities.DevProRelation_Tab.Add(dprt);
                    Entities.Entry<DevProRelation_Tab>(dprt).State = System.Data.Entity.EntityState.Modified;
                }
                code = Entities.SaveChanges();
                if (code > 0)
                {
                    //获取设备信息
                    DevInfo_Tab DevModel = Entities.DevInfo_Tab.Where(i => i.DeviceId == drim.DeviceId).FirstOrDefault();
                    DevModel.State = drim.State;

                    Entities.DevInfo_Tab.Add(DevModel);
                    Entities.Entry<DevInfo_Tab>(DevModel).State = System.Data.Entity.EntityState.Modified;
                    code = Entities.SaveChanges();
                    SetSonDevInfo(DevModel.ID, DevModel.DeviceId, drim.State);
                    return Content("{\"msg\":\"修改成功！\",\"success\":true}");
                }
                else
                {
                    return Content("{\"msg\":\"修改成功！入库失败\",\"success\":false}");
                }
            }
        }


        /// <summary>
        /// 根据ID改变设备状态
        /// </summary>
        /// <returns></returns>
        public ActionResult DelDevProRelation()
        {
            string DeviceId = Request["DeviceId"];
            int Code = 0;
            string msg = "";
            using (CYOADBEntities Entities = new CYOADBEntities())
            {
                //获取当前设备的关系信息
                DevProRelation_Tab dprt = Entities.DevProRelation_Tab.Where(i => i.DeviceId == DeviceId).FirstOrDefault();
                DevInfo_Tab DevModel = Entities.DevInfo_Tab.Where(i => i.DeviceId == DeviceId).FirstOrDefault();

                if (dprt != null)
                {
                    if (DevModel.DeviceLevel > 1)
                    {
                        return Content("{\"msg\":\"当前设备等级不是1级，不能报废！\",\"success\":false}");
                    }
                    dprt.ScrapTime = System.DateTime.Now;
                    Entities.DevProRelation_Tab.Add(dprt);
                    Entities.Entry<DevProRelation_Tab>(dprt).State = System.Data.Entity.EntityState.Modified;
                    DevModel.State = (int)DevState.Scrap;

                    Entities.DevInfo_Tab.Add(DevModel);
                    Entities.Entry<DevInfo_Tab>(DevModel).State = System.Data.Entity.EntityState.Modified;
                    Code = Entities.SaveChanges();
                    SetSonDevInfo(DevModel.ID, DevModel.DeviceId, (int)DevState.Scrap);
                }
                else
                {
                    Code = -1;
                    msg = "未查询到信息，无法报废";
                }
            }
            if (Code > 0)
            {
                return Content("{\"msg\":\"报废成功！\",\"success\":true}");
            }
            else
            {
                return Content("{\"msg\":\"报废失败！" + msg + "\",\"success\":false}");
            }
        }
    }

}
